//
//  PhoneVerificationViewController.m
//  Exchange
//
//  Created by 张庆勇 on 2018/8/2.
//  Copyright © 2018年 张庆勇. All rights reserved.
//

#import "PhoneVerificationViewController.h"
#import "CountryModle.h"
#import "CountryListsViewController.h"
@interface PhoneVerificationViewController ()

@property (nonatomic,strong)NSMutableArray *dataArray;
@property (nonatomic,strong)NSString *country_id;
@end

@implementation PhoneVerificationViewController
- (void)dealloc
{
    [self.Verificationbutton stopTime];
    self.Verificationbutton = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self customUI];
    [self getcountry];
     _country_id = @"44";
    _areaLable.text = [NSString stringWithFormat:@"%@ %@",Localized(@"China"),@"+86"];
}
- (void)getcountry
{
    WeakSelf
    [self GETWithHost:@"" path:countryHttp param:@{} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([responseObject[@"code"] integerValue] ==0)//成功
        {
            NSArray * list = responseObject[@"result"];
            for (NSDictionary * dic in list)
            {
                CountryModle * modle = [[CountryModle alloc] init];
                modle.CreatedAt = dic[@"CreatedAt"];
                modle.ID = dic[@"ID"];
                modle.UpdatedAt = dic[@"UpdatedAt"];
                modle.country_code = dic[@"code"];
                modle.is_show = dic[@"is_show"];
                modle.name_cn = dic[@"name_cn"];
                modle.name_en = dic[@"name_en"];
                modle.area_code = dic[@"area_code"];
                modle.pinyin = [self transform:[EXUnit removeCharacter:modle.name_cn]];
                [weakSelf.dataArray addObject:modle];
            }
        }else
        {
            [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
        }
    } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (NSString *)transform:(NSString *)chinese{
    //将NSString装换成NSMutableString
    NSMutableString *pinyin = [chinese mutableCopy];
    
    //将汉字转换为拼音(带音标)
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformMandarinLatin, NO);
    
    //去掉拼音的音标
    CFStringTransform((__bridge CFMutableStringRef)pinyin, NULL, kCFStringTransformStripCombiningMarks, NO);
    NSLog(@"%@", pinyin);
    
    //返回最近结果
    return pinyin;
    
}
- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (void)customUI
{
    self.view.backgroundColor = MainBGCOLOR;
    _bgView1.backgroundColor = textFieldColor;
    _bgview.backgroundColor = textFieldColor;
    _nextbutton.backgroundColor = TABTITLECOLOR;
    _areaLable.adjustsFontSizeToFitWidth = YES;
    _areaLable.textColor = MAINTITLECOLOR;
    
    _phoneTitle.text = Localized(@"bank_phone");
    _verificationTitle.text = Localized(@"Security_phone_code");
    _phoneTextfield.placeholder = Localized(@"register_phone_number");
    _phoneVerification.placeholder = Localized(@"Security_phone_code_message");

    
    [_nextbutton setTitle:Localized(@"Security_Next_step") forState:0];

    if ([[EXUnit isLocalizable] isEqualToString:@"en"]) {
        [_phoneVerification setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
        [_phoneVerification setValue:AutoFont(10) forKeyPath:@"_placeholderLabel.font"];
        
        [_phoneTextfield setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
        [_phoneTextfield setValue:AutoFont(10) forKeyPath:@"_placeholderLabel.font"];
    }else
    {
        [_phoneVerification setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
        [_phoneVerification setValue:AutoFont(13) forKeyPath:@"_placeholderLabel.font"];
        
        [_phoneTextfield setValue:textFieldPCOLOR forKeyPath:@"_placeholderLabel.textColor"];
        [_phoneTextfield setValue:AutoFont(13) forKeyPath:@"_placeholderLabel.font"];
    }
    _phoneTextfield.tintColor = TABTITLECOLOR;
    _phoneTextfield.textColor = MAINTITLECOLOR;
  
    _phoneVerification.tintColor = MAINTITLECOLOR;
    _phoneVerification.textColor = MAINTITLECOLOR;
    KViewRadius(self.nextbutton, 2);
    RACSignal*phoneSignal=[_phoneTextfield.rac_textSignal map:^id(NSString* value) {
        return @(value.length>3);
    }];
    RACSignal*phoneVeriSignal=[_phoneVerification.rac_textSignal map:^id(NSString* value) {
        return @([EXUnit CodeissSixplace:value]);
    }];
    RACSignal*Signal=[RACSignal combineLatest:@[phoneSignal,phoneVeriSignal] reduce:^id(NSNumber*emailValid,NSNumber*emailVerValid){
        return @([emailValid boolValue]&&[emailVerValid boolValue]);
    }];
    WeakSelf
    [Signal subscribeNext:^(NSNumber* x) {
        
        if ([x boolValue]) {
            weakSelf.nextbutton.enabled=YES;
            weakSelf.nextbutton.alpha = 1;
            
        }else
        {
            weakSelf.nextbutton.enabled=NO;
            weakSelf.nextbutton.alpha = 0.5;
        }
    }];
    
    // 倒计时的时长
    _Verificationbutton.title = Localized(@"register_phone_verification_code");
    _Verificationbutton.totalSecond = 60;
    [_Verificationbutton setTitleColor:TABTITLECOLOR forState:0];
    _Verificationbutton.titleLabel.adjustsFontSizeToFitWidth = YES;
    [_Verificationbutton processBlock:^(NSUInteger second)
     {
         weakSelf.Verificationbutton.title = [NSString stringWithFormat:@"%lis", (unsigned long)second] ;
     } onFinishedBlock:^{  // 倒计时完毕
         weakSelf.Verificationbutton.title = Localized(@"Regain_validation_code");
     }];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (IBAction)verificationbutton:(QCCountdownButton *)sender {
    if ([NSString isEmptyString:_phoneTextfield.text]) {
        
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_phone_number_message") view:kWindow];
    }else if (_phoneTextfield.text.length ==0)
    {
        [self axcBasePopUpWarningAlertViewWithMessage:Localized(@"register_phone_number") view:kWindow];
    }else
    {
        
        [self POSTWithHost:@"" path:userSMS param:@{@"type":@(0),@"use_type":@(4),@"phone":_phoneTextfield.text,@"country_id":_country_id} cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                [self.Verificationbutton startTime];
            }else
            {
                [self axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}

- (IBAction)nextbutton:(UIButton *)sender {
    
//    _phoneVerification.
     [_phoneTextfield resignFirstResponder];
     [_phoneVerification resignFirstResponder];
    CustomAlertVC * custom = [[CustomAlertVC alloc] initWithCustomContentViewClass:@"BindCustonAlert" delegate:nil];
    custom.direction = FromBottom;
    [custom show];
    BindCustonAlert *aleatView = (BindCustonAlert *)custom.contentView;
    aleatView.type = @"4";
    aleatView.isBindGoole = NO;
    aleatView.cancelBlock = ^{
        [custom dismiss];
    };
    WeakSelf
    WeakObject(aleatView)
    [aleatView.okButton add_BtnClickHandler:^(NSInteger tag) {
        
        
        if (![NSString isEmptyString:weakaleatView.emailField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.emailField.text]) {
           
                 [EXUnit showMessage:Localized(@"VerificationMessage")];
                return ;
            }
        }
        if (![NSString isEmptyString:weakaleatView.phoneField.text])
        {
            if (![EXUnit CodeissSixplace:weakaleatView.phoneField.text]) {
               [EXUnit showMessage:Localized(@"VerificationMessage")];
                return ;
            }
        }
        NSDictionary * param = @{@"phone":weakSelf.phoneTextfield.text,
                                 @"sms_code":weakSelf.phoneVerification.text,
                                 @"email_code":[NSString isEmptyString:weakaleatView.emailField.text]?@"":weakaleatView.emailField.text,
                                 @"country_id":weakSelf.country_id,
                                 @"two_step_code":[NSString isEmptyString:weakaleatView.gooldField.text]?@"":weakaleatView.gooldField.text};
        
        [weakSelf POSTWithHost:@"" path:bindPhone param:param cache:NO completed:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
             [weakaleatView.okButton stopAnimation];
            if ([responseObject[@"code"] integerValue]==0)//成功
            {
                [EXUserManager savephone:@"1"];
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
                [custom dismiss];
                
                 [[NSNotificationCenter defaultCenter] postNotificationName:SetSecurityNotificationse object:nil];
                [self.navigationController popViewControllerAnimated:YES];
                
            }else
            {
                [weakSelf axcBasePopUpWarningAlertViewWithMessage:responseObject[@"message"] view:kWindow];
            }
            
        } error:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              [weakaleatView.okButton stopAnimation];
        }];
        
    }];
}
- (IBAction)choosebutton:(UIButton *)sender {
    WeakSelf
    CountryListsViewController * CountryListVC = [[CountryListsViewController alloc] init];
    CountryListVC.dataArray = self.dataArray;
    CountryListVC.index = self.country_id.integerValue;
    [self presentViewController:CountryListVC animated:YES completion:nil];
    CountryListVC.selectIndexPathRow = ^(CountryModle *modle) {
        self.country_id = modle.ID;
        if ([[EXUnit  isLocalizable]  hasPrefix:@"zh-Hant"] || [[EXUnit  isLocalizable]  hasPrefix:@"zh-Hans"] ) {
            weakSelf.areaLable.text = [NSString stringWithFormat:@"%@ %@",modle.name_cn,modle.area_code];
        }else
        {
            weakSelf.areaLable.text = [NSString stringWithFormat:@"%@ %@",modle.name_en,modle.area_code];
        }
    };
}
@end
